from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.decorators import login_required
from tribes.models import Tribe
from books.models import Book
from django.contrib.contenttypes.models import ContentType

@login_required
def new(request, content_type_id, object_id, 
            template_name="books/new.html"):
    """
    creates a new book
    """
    from books.forms import NewBookForm
    
    # if a new book was posted
    if request.method == 'POST':
        book_form = NewBookForm(request.POST)
        if book_form.is_valid():
            # create it
            book = book_form.save(commit=False)
            content_type        = \
                ContentType.objects.get(id=content_type_id)
            content_object      = \
                content_type.get_object_for_this_type(
                id=object_id)
            book.content_object = content_object
            book.save()
            request.user.message_set.create(
                message=
                _("Successfully created book '%s'")
                % book.name)
            # send to object page or book page
            try:
                return HttpResponseRedirect(
                    content_object.get_absolute_url()
                )
            except:
                return HttpResponseRedirect(reverse(
                    'book_details', args=(book.id,)))
        # if invalid, it gets displayed below
    else:
        book_form = NewBookForm()
    
    
    return render_to_response(template_name, {
        'book_form': book_form,
    }, context_instance=RequestContext(request))

@login_required
def details(request, book_id, 
    template_name="books/details.html"):
    """
    displays details of a book
    """
    
    book = get_object_or_404(Book, id=book_id)
    
    return render_to_response(template_name, {
        'book': book,
    }, context_instance=RequestContext(request))
    
    
    
